<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/7/4 下午2:45
 * +-------------------------------------------------------------
 */

namespace app\admin\validate;

use think\Validate;

class ProductValidate extends Validate
{
    protected $rule = [
            'cate_id'      => 'require',
            'title'        => 'require|max:30',
            'intro'        => 'require|max:100',
            'describe'     => 'require',
            'specs'        => 'require|checkSpecs',
            'product_day'  => 'require|gt:0',
    ];

    protected $message = [
            'cate_id.require'         => '分类不能为空',
            'title.require'           => '标题不能为空',
            'title.max'               => '标题最多不能超过30个字符',
            'intro.require'           => '简介不能为空',
            'intro.max'               => '简介最多不能超过100个字符',
            'describe.require'        => '描述不能为空',
            'specs.require'           => '规格不能为空',
            'specs.checkSpecs'        => '规格参数错误',
            'product_day.require'     => '保质期不能为空',
            'product_day.gt'          => '保质期必须大于0',
    ];

    protected $scene = [
            'add'       => ['cate_id', 'title', 'intro', 'describe', 'specs','product_day']
    ];

    protected function checkSpecs($value): bool
    {
        // 验证JSON格式
        $specs = json_decode($value,true);
        // 验证JSON数据结构
        $index = 0;
        foreach ($specs as $spec) {
            $index++;
            if(!$spec['title']){
                $this->message['specs.checkSpecs'] = '第'.$index.'个规格名称不能为空';
                return false;
            }
            if(!$spec['market_price']){
                $this->message['specs.checkSpecs'] = '第'.$index.'个规格市场价不能为空';
                return false;
            }
            if($spec['market_price'] <=0 ){
                $this->message['specs.checkSpecs'] = '第'.$index.'个规格市场价必须大于0';
                return false;
            }
            if(!$spec['take_price']){
                $this->message['specs.checkSpecs'] = '第'.$index.'个规格提货价不能为空';
                return false;
            }
            if($spec['take_price'] <=0 ){
                $this->message['specs.checkSpecs'] = '第'.$index.'个规格提货价必须大于0';
                return false;
            }
        }
        return true;
    }
}